<?php
// 设置地址
require_once $this->website['path']['action'] . '/app/token.php'; //$basic['uid']
$json = array('status' => 'error', 'msg' => '', 'data' => '');

$sys = fn_configura($this->website, "sys");

$uid = $basic['uid'];

$id = fn_post('id');
$phone = fn_post('phone');
$def = fn_post('def');
$province = fn_post('province');
$city = fn_post('city');
$district = fn_post('district');
$tit = fn_post('tit');
$addr = fn_post('addr');
$tm = fn_post('tm');

if (!$phone) {
	$json['msg'] = '请输入联系号码';
} elseif (!$province) {
	$json['msg'] = '请选择省份';
} elseif (!$city) {
	$json['msg'] = '请选择省份';
} elseif (!$district) {
	$json['msg'] = '请选择省份';
} elseif (!$tit) {
	$json['msg'] = '请输入收货人姓名';
} elseif (!$addr) {
	$json['msg'] = '请输入详细地址';
} elseif (!$tm) {
	$json['msg'] = '请选在收货时间';
} else {
	if ($id) {
		// update
		if (!$this->website['class']['db']
			->table('user_address')
			->where('id=? and uid=?', $id, $uid)
			->limit(1)
			->count()) {
			$json['msg'] = '地址不存在或已被删除';
			$this->json_encode_encrypt($json);
		} else {
			$this->website['class']['db']
				->table('user_address')
				->field('phone', 'def', 'province', 'city', 'district', 'tit', 'addr', 'tm')
				->value($phone, $def, $province, $city, $district, $tit, $addr, $tm)
				->where('id=? and uid=?', $id, $uid)
				->limit(1)
				->update();
			$json['status'] = 'ok';
			if ($id && $def == "1") {
				$this->website['class']['db']
					->table('user_address')
					->field('def')
					->value(0)
					->where('uid=? and id !=?', $uid, $id)
					->update();
			}
		}
	} elseif ($this->website['class']['db']
			->table('user_address')
			->where('uid=?', $uid)
			->count() >= $sys['addrmaxnum']) {
		$json['msg'] = '地址最多' . $sys['addrmaxnum'] . '条';
	} else {
//insert
		$id = $this->website['class']['db']
			->table('user_address')
			->field('uid', 'phone', 'def', 'province', 'city', 'district', 'tit', 'addr', 'tm')
			->value($uid, $phone, $def, $province, $city, $district, $tit, $addr, $tm)
			->insert();
		$json['status'] = 'ok';
		if ($id && $def == "1") {
			$this->website['class']['db']
				->table('user_address')
				->field('def')
				->value(0)
				->where('uid=? and id !=?', $uid, $id)
				->update();
		}
	}

}
// $json['sql'] = $this->website['class']['db']->sql;

$this->json_encode_encrypt($json);
